<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="defName" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="defAge" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="defGender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加</button>
      <button @click="update">修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(val, index) in arr" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ val.name }}</td>
          <td>{{ val.age }}</td>
          <td>{{ val.gender }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      defName: "",
      defAge: "",
      defGender: "",
      arr: [
        {
          name: "tom",
          age: 19,
          gender: "男",
        },
        {
          name: "jone",
          age: 21,
          gender: "女",
        },
      ],
    };
  },
  methods: {
    // 添加功能
    add() {
      if (this.defName == "" || this.defAge == "" || this.defGender == "") {
        alert("请输入正确的姓名,年龄和性别");
      } else {
        this.arr.push({
          name: this.defName,
          age: this.defAge,
          gender: this.defGender,
        });
      }
    },
    edit(index) {
      this.defName = this.arr[index].name;
      this.defAge = this.arr[index].age;
      this.defGender = this.arr[index].gender;
    },
    update() {
      //暂未实现
      // this.arr.splice(this.arr.index - 1, 0, {
      //   name: this.defName,
      //   age: this.defAge,
      //   gender: this.defGender,
      // });
      // console.log(this.arr.index);
    },
    del(index) {
      this.arr.splice(index, 1);
    },
  },
};
</script>
